package com.springboot.news.interceptors;

        import com.springboot.news.utils.JwtUtil;
        import com.springboot.news.utils.ThreadLocalUtil;
        import org.springframework.stereotype.Component;
        import org.springframework.web.servlet.HandlerInterceptor;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.util.Map;

@Component
public class LoginInterceptors implements HandlerInterceptor {
    //    threadLocal
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws  Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
//            threadLocal 存数据
            return true;
        }catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        清除缓存
        ThreadLocalUtil.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
